package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.ExportExcel;
import com.example.reggie.common.R;
import com.example.reggie.entity.*;
import com.example.reggie.service.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.beans.IntrospectionException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/order")
public class OrdersController {

    /*订单*/
    @Autowired
    private OrdersService ordersService;

    /*用户信息*/
    @Autowired
    private UserService userService;

    /*地址*/
    @Autowired
    private AddressBookService addressBookService;

    /*购物车*/
    @Autowired
    private ShoppingCartService shoppingCart;

    /*订单明细*/
    @Autowired
    private OrderDetailService orderDetailService;

    /*去支付，生成订单*/
/*    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders, HttpServletRequest request){

        System.out.println("111111111111111111111111111111111111111111111111111"+orders);


        *//*获得当前用户id, 查询当前用户的购物车数据*//*
        Long userId = (Long) request.getSession().getAttribute("user");
        //查询当前用户的购物车数据
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCarts = shoppingCart.list(wrapper);

        //查询用户数据
        User user = userService.getById(userId);

        //查询地址数据
*//*        Long addressBookId = orders.getAddressBookId();
        AddressBook addressBook = addressBookService.getById(addressBookId);*//*
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userId);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
        if (addressBook==null){
            throw new CustomException("请先去添加地址");
        }


        long orderId = IdWorker.getId();//订单号

        *//*防止丢失精度*//*
        AtomicInteger amount = new AtomicInteger(0);

        //组装订单明细信息
        List<OrderDetail> orderDetails = shoppingCarts.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setOrderId(orderId);
            orderDetail.setNumber(item.getNumber());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setAmount(item.getAmount());
            amount.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //组装订单数据
        orders.setId(orderId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        orders.setAmount(new BigDecimal(amount.get()));//总金额
        orders.setUserId(userId);
        orders.setNumber(String.valueOf(orderId));
        orders.setUserName(user.getName());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPhone(addressBook.getPhone());
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        //向订单表插入数据，一条数据
        ordersService.save(orders);

        //向订单明细表插入数据，多条数据
        orderDetailService.saveBatch(orderDetails);

        //清空购物车数据
        shoppingCart.remove(wrapper);


        return R.success("下单成功");
    }*/

    /**
     * 去支付，生成订单
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders, HttpServletRequest request){

            //获取用户id
            Long userId = (Long) request.getSession().getAttribute("user");
            //1.查看购物车数据
            LambdaQueryWrapper<ShoppingCart> qw = new LambdaQueryWrapper<>();
            qw.eq(ShoppingCart::getUserId, userId);
            List<ShoppingCart> shoppingCartList = shoppingCart.list(qw);
            //2.查看用户数据
            User user = userService.getById(userId);
            //3.查看收货地址
/*            Long addressBookId = orders.getAddressBookId();
            AddressBook addressBook = addressBookService.getById(addressBookId);*/
        LambdaQueryWrapper<AddressBook> addressBookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        addressBookLambdaQueryWrapper.eq(AddressBook::getUserId,userId).eq(AddressBook::getIsDefault,1);
        AddressBook addressBook = addressBookService.getOne(addressBookLambdaQueryWrapper);
/*        if (addressBook==null){
                System.out.println(addressBook);
                throw new CustomException("地址为空");
            }*/
            //生成订单号
            Long orderNumber = IdWorker.getId();
            //总价初始值
            BigDecimal amount = new BigDecimal("0");

            // 4、保存订单明细数据：点了哪些菜品或套餐
            for (ShoppingCart shop : shoppingCartList) {
                //订单详情实体类
                OrderDetail orderDetail = new OrderDetail();
                BeanUtils.copyProperties(shop, orderDetail);
                //手动赋值订单id
                orderDetail.setOrderId(orderNumber);
                //计算价格 数量 * 单价
                BigDecimal price = shop.getAmount();
                BigDecimal number = BigDecimal.valueOf(shop.getNumber());
                orderDetail.setAmount(price.multiply(number));
                amount = amount.add(orderDetail.getAmount());//一种菜品的价格，累加
//存入订单详情表中
//                orderDetailDao.insert(orderDetail);
                orderDetailService.save(orderDetail);
            }
            System.out.println("amount = " + amount);
            // 5、保存订单数据，有许多数据需要单独设置
            orders.setNumber(String.valueOf(orderNumber));  //订单号
            orders.setAmount(amount);   //订单总价
            orders.setOrderTime(LocalDateTime.now());   //下单时间
            orders.setCheckoutTime(LocalDateTime.now());    //结账时间
            orders.setUserId(userId);
            orders.setConsignee(addressBook.getConsignee());    //设置收件人姓名
            orders.setUserName(user.getName()); //设置用户名
            orders.setPhone(user.getPhone());   //设置手机号
            orders.setStatus(2);//1待付款，2待派送，3已派送，4已完成，5已取消
            orders.setAddress(
                    (addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                            + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                            + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                            + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));//省+市+区域+详细地址

        orders.setAddressBookId(addressBook.getId());
            ordersService.save(orders);
            // 6、删除当前用户的购物车数据
            LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(ShoppingCart::getUserId, userId);
//            shoppingCartService.remove(wrapper);
            shoppingCart.remove(wrapper);
            return R.success("清空购物车成功");
        }

    @GetMapping("/userPage")
    public R userPage(Integer page,Integer pageSize){
        IPage<Orders> iPage = ordersService.page(new Page<>(page, pageSize));
        return R.success(iPage);
    }


    /*管理段的分页查询*/
    @GetMapping("/page")
    public R page(Integer page, Integer pageSize, Integer number, @DateTimeFormat(pattern = "yyyy-mm-dd") Date beginTime,
                  @DateTimeFormat(pattern = "yyyy-mm-dd") Date endTime){
        LambdaQueryWrapper<Orders> ordersLambdaQueryWrapper = new LambdaQueryWrapper<>();
        ordersLambdaQueryWrapper.like(number!=null,Orders::getNumber,number);

        ordersLambdaQueryWrapper.ge(beginTime!=null,Orders::getOrderTime,beginTime);
        ordersLambdaQueryWrapper.le(endTime!=null,Orders::getCheckoutTime,endTime);


        IPage<Orders> iPage = ordersService.page(new Page<>(page, pageSize),ordersLambdaQueryWrapper);



        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
/*        wrapper.eq()*/


        return R.success(iPage);
    }
    /*管理派送*/
    @PutMapping
    public R order(@RequestBody Orders orders){
        System.out.println("用于查看111111111111111111:"+orders.getId());
        Orders one = ordersService.getById(orders.getId());
//订单状态 1待付款，2待派送，3已派送，4已完成，5已取消
        System.out.println("用于查看111111111111111111:"+one);
        one.setStatus(4);

        ordersService.updateById(one);
        return R.success("修改成功");
    }

    /*订单明细中新增一个Excel导出功能*/
    @GetMapping("/export")
    public R export(HttpServletRequest request, HttpServletResponse response) throws IntrospectionException, InvocationTargetException, IllegalAccessException, IOException {

        List<Orders> list = ordersService.list();
        System.out.println("lllllllllllllllllllllllllllll"+list);

        try
        {
            FileOutputStream fout = new FileOutputStream("D:/订单明细.xls");
            new ExportExcel().getValue(list, fout);
            fout.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return R.success("成功");
    }
}
